<?php


namespace app\phIndex\service;


use think\facade\Db;
use think\View;

class Service extends View
{
    //验证登录
    public function is_login()
    {
        if (!session('user')) {
            redirect(url('login'))->send();
        }
    }

    //获取用户id
    public function getLoginUserId()
    {
        $mobile = session('user');
        if (!empty($mobile)) {
            $res = Db::table('user')->field('id')->where('mobile', '=', $mobile)->find();
            if ($res) {
                return $res['id'];
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    //验证用户密码
    public function checkPassword($mobile, $pwd): bool
    {
        $res = Db::table('user')->field('id')->where('mobile', '=', $mobile)->find();
        if ($res) {
            $userId = $res['id'];
            $res = Db::table('user')->field('password')->where(['id' => $userId])->find();
            if ($res) {
                return $res['password'] === $pwd;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    //更新登录时间
    public function loginTime()
    {
        $userId = $this->getLoginUserId();
        if (!empty($userId)) {
            $res = Db::table('user')->where('id', '=', $userId)->data([
                'last_login_time' => time()
            ])->update();
        }
    }
}